package yifeng.thread;

import java.util.Random;

public class T1 {

	private static Object lock = new Object();
	private static int i = 0;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					synchronized (lock) {
						while(i <= 0){
							try {
								lock.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}

						System.out.println(Thread.currentThread().getName() 
								+ "is consuming!Currently i = " + i);
					}
					
					
					try {
						Thread.sleep(new Random().nextInt(2000)+2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					
					synchronized(lock){
						i--;
					}
				}
			}
		}, "Consumer").start();

		
		
		
		
		Thread.currentThread().setName("Producer");
		while (true) {
			try {
				Thread.sleep(new Random().nextInt(2000)+1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (lock) {
				i++;
				lock.notify();
			}
		}
	}

}
